<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="control-section">
      <!-- <div>
        <el-button @click="mergedata">merge</el-button>
      </div> -->
      <div class="content-wrapper" v-loading="loading">
        <ejs-grid
          v-if="isHasData"
          :style="{ height: gadgetHeight + 'px' }"
          :dataSource="gridDefaultSetting.dataSource"
          :allowResizing="gridDefaultSetting.allowResizing"
          :allowFiltering="gridDefaultSetting.allowFiltering"
          :filterSettings="gridDefaultSetting.filterSettings"
          :allowGrouping="gridDefaultSetting.allowGrouping"
          :allowPaging="gridDefaultSetting.allowPaging"
          :height="gadgetHeight - 215"
          :toolbar="gridDefaultSetting.toolbar"
          :allowTextWrap="gridDefaultSetting.allowTextWrap"
          :showColumnChooser="gridDefaultSetting.showColumnChooser"
          :allowReordering="gridDefaultSetting.allowReordering"
          :allowSorting="gridDefaultSetting.allowSorting"
          :load="load"
          :dataBound ="dataBound"
          :recordClick="recordClick"
          :pageSettings="pageSettings"
          ref="datagrid"
        >
        </ejs-grid>
        <div v-else class="gadget-no-data">
          <el-image
            @click="query()"
            :src="noDataImageUrl"
            fit="fill"
          ></el-image>
        </div>
      </div>
    </div>
    <model
      :showSetting="queryModelDefaultSetting.showSetting"
      @queryModelClosed="queryModelClosed"
      :dataInfo="queryModelDefaultSetting.dataInfo"
      :updateGadget="upgradeGadgetSetting"
    />
  </el-card>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import mixinViewModule from '@/mixins/simplereport-view-module'
import ReportPathFormat from '@/components/gadget/customized/menuList/ReportPathFormat.vue'

export default {
  mixins: [mixinGadgetViewModule, mixinViewModule],
  components: { ReportPathFormat, model: () => import('@/components/gadget/query-model/query-model') },

  data () {
    return {
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      reportSetting: null,
      pageSettings: { pageSize: 100, pageSizes: [50, 100, 200, 1000], pageCount: 4 },
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'menulistgadget',
          gadgetSetting: {}
        }
      },
      reportName: '',
      ReportPathFormat: function () {
        return { template: ReportPathFormat }
      }
    }
  },

  created () {
    this.subscribeMessage('runReport', this.query)
    this.query()
    this.$store.state.isWidget = false
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    }
  },
  methods: {
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.gadgetInfo.h * 20 - 60
    },
    findColumnIndex (arr) {
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index]
        if (element.field === 'Name') {
          return index
        }
      }
      return -1
    },
    recordClick (args) {
      if (args.column.field === 'Name') {
        if (!this.$hasPermissionRouterName(args.rowData.Name.replace(/ /g, ''))) {
          return this.$message.error(this.$t('prompt.nopermission'))
        } else {
          this.$router.push({ path: args.rowData.Path, query: { pageid: args.rowData.PageId } })
        }
      }
    },
    applyGadgetSetting () {
      var groupSettings = { groupSettings: this.reportSetting.groupSettings }
      delete this.reportSetting.groupSettings

      var filterSettings = { filterSettings: this.reportSetting.filterSettings }
      delete this.reportSetting.filterSettings

      // process link column
      var index = this.findColumnIndex(this.reportSetting.columns)
      if (index >= 0) {
        this.reportSetting.columns[index].template = this.ReportPathFormat
      }

      this.grid.ej2Instances.setProperties(this.reportSetting)
      this.grid.ej2Instances.setProperties(filterSettings)
      this.grid.ej2Instances.setProperties(groupSettings)
    },
    mergedata () {
      this._.merge(this.reportSetting, JSON.parse(this.grid.ej2Instances.getPersistData()))
      this.applyGadgetSetting()
    },
    saveGadgetSetting () {
      var _self = this
      _self.reportSetting = JSON.parse(this.grid.ej2Instances.getPersistData())
      // grid table , save obj  from json obj
      const params = {
        businessId: this.mixinViewModuleOptions.pageId,
        gadgetSetting: _self.reportSetting,
        gadgetId: this.id,
        type: 1
      }
      this.$interface.reports.postReportSetting(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
      })
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - 60
      this.gadgetWidth = newWPx
    },
    query (ignoreColumn) {
      this.isHasData = false
      this.loading = true
      var _self = this

      var param = {
        ...this.slicer,
        pageId: this.pageId,
        gadgetId: this.id,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          // process data
          if (param.current) {
            _self.gridDefaultSetting.dataSource = res.data.records
            this.pageOptions.total = res.data.total * 1
            this.pageOptions.currentPage = res.data.current * 1
          } else {
            _self.gridDefaultSetting.dataSource = res.data
          }

          // process config
          if (!ignoreColumn) {
            if (res.config) {
              _self.reportSetting = res.config.report || res.config
              _self.queryModelDefaultSetting.dataInfo.gadgetSetting = _self.reportSetting
              _self.isGridInit = false
            }
          }
          _self.isHasData = true
          this.loading = false
        })
        .catch(() => {})
    }
  }
}
</script>
<style scoped>
.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}
</style>
